package com.survey.wxapp.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.survey.common.core.redis.RedisCache;
import com.survey.wxapp.common.wxconfig.DisWxuserConstants;
import com.survey.wxapp.login.util.HttpClientUtil;
import com.survey.wxapp.service.WxLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 微信用户Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-26
 */
@Service
public class DisWxuserServiceImplWxapp implements WxLoginService {

    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private RedisCache redisCache;

    @Override
    public String getWxOpenid(String code) {
        String appid = DisWxuserConstants.APPID;
        String secret = DisWxuserConstants.STRING;
//        拼接sql
        String loginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid +
                "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";

        String result = httpClientUtil.sendHttpGet(loginUrl);
        if (result != null) {
            JSONObject jsonObject = JSON.parseObject(result);//将json字符串转化为jsonobject
            Object openid = jsonObject.get("openid");
            Object sessionKey = jsonObject.get("session_key");
            redisCache.setCacheObject("session_key", sessionKey);
            if (openid != null) {
                return openid.toString();
            }
        }
        return null;
    }
}
